const pool = require('../config/database');

class AdlAssessmentModel {
  /**
   * 创建老年人生活自理能力评估记录
   * @param {Object} assessmentData - 评估数据
   * @returns {Promise<Object>} 创建的评估记录
   */
  static async create(assessmentData) {
    const connection = await pool.getConnection();
    
    try {
      await connection.beginTransaction();
      
      const fields = Object.keys(assessmentData);
      const values = Object.values(assessmentData);
      const placeholders = fields.map(() => '?').join(', ');
      
      const sql = `
        INSERT INTO jktj_adl_assessment (${fields.join(', ')})
        VALUES (${placeholders})
      `;
      
      const [result] = await connection.execute(sql, values);
      
      await connection.commit();
      
      return {
        id: result.insertId,
        ...assessmentData
      };
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  /**
   * 根据体检ID获取评估记录
   * @param {number} tjId - 体检ID
   * @returns {Promise<Object>} 评估记录
   */
  static async findByTjId(tjId) {
    const sql = 'SELECT * FROM jktj_adl_assessment WHERE tj_id = ?';
    const [rows] = await pool.execute(sql, [tjId]);
    return rows[0] || null;
  }

  /**
   * 根据ID获取评估记录
   * @param {number} id - 评估记录ID
   * @returns {Promise<Object>} 评估记录
   */
  static async findById(id) {
    const sql = 'SELECT * FROM jktj_adl_assessment WHERE id = ?';
    const [rows] = await pool.execute(sql, [id]);
    return rows[0] || null;
  }

  /**
   * 更新评估记录
   * @param {number} tjId - 体检ID
   * @param {Object} updateData - 更新数据
   * @returns {Promise<boolean>} 更新结果
   */
  static async update(tjId, updateData) {
    const fields = Object.keys(updateData);
    const values = Object.values(updateData);
    const setClause = fields.map(field => `${field} = ?`).join(', ');
    
    const sql = `UPDATE jktj_adl_assessment SET ${setClause} WHERE tj_id = ?`;
    const [result] = await pool.execute(sql, [...values, tjId]);
    
    return result.affectedRows > 0;
  }

  /**
   * 删除评估记录
   * @param {number} tjId - 体检ID
   * @returns {Promise<boolean>} 删除结果
   */
  static async delete(tjId) {
    const sql = 'DELETE FROM jktj_adl_assessment WHERE tj_id = ?';
    const [result] = await pool.execute(sql, [tjId]);
    return result.affectedRows > 0;
  }

  /**
   * 计算ADL总分
   * @param {Object} assessmentData - 评估数据
   * @returns {number} 总分
   */
  static calculateTotalScore(assessmentData) {
    const { q1, q2, q3, q4, q5 } = assessmentData;
    const scores = [q1, q2, q3, q4, q5].map(score => parseInt(score) || 0);
    return scores.reduce((total, score) => total + score, 0);
  }

  /**
   * 根据总分判断自理能力等级
   * @param {number} totalScore - 总分
   * @returns {string} 自理能力等级
   */
  static getAbilityLevel(totalScore) {
    if (totalScore >= 0 && totalScore <= 3) {
      return '1'; // 可自理
    } else if (totalScore >= 4 && totalScore <= 8) {
      return '2'; // 轻度依赖
    } else if (totalScore >= 9 && totalScore <= 18) {
      return '3'; // 中度依赖
    } else if (totalScore >= 19) {
      return '4'; // 不能自理
    }
    return '1'; // 默认可自理
  }
}

module.exports = AdlAssessmentModel;